package org.example.back.service.advice;

import org.example.back.entity.user.UserMeal;
import org.example.back.entity.user.UserMealFood;
import org.example.back.mapper.user.UserMealMapper;
import org.example.back.mapper.advice.UserMealAdviceMapper;
import org.example.back.service.healthassistant.HealthAssistantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class UserMealAdviceService {

    @Autowired
    private UserMealMapper userMealMapper;

    @Autowired
    private UserMealAdviceMapper userMealAdviceMapper;

    @Autowired
    private HealthAssistantService healthAssistantService;

    /**
     * 获取日建议（按天缓存）
     */
    public String getDailyAdvice(Integer userId, LocalDate date) {
        String cached = userMealAdviceMapper.findAdvice(userId, "day", date);
        if (cached != null) return cached;

        List<UserMeal> meals = userMealMapper.findMealsByDate(userId, date);
        if (meals == null || meals.isEmpty()) {
            return "您在 " + date + " 没有记录饮食信息，请保持记录以获得个性化建议。";
        }

        StringBuilder sb = new StringBuilder("以下是您 ").append(date).append(" 的饮食记录：\n");

        for (UserMeal meal : meals) {
            sb.append(String.format("时间：%s，类型：%s，总热量：%.1f 千卡，蛋白质：%.1fg，脂肪：%.1fg，碳水：%.1fg，纤维：%.1fg\n",
                    meal.getMealTime(), meal.getMealType(),
                    getDouble(meal.getCalories()), getDouble(meal.getProtein()),
                    getDouble(meal.getFat()), getDouble(meal.getCarbohydrate()),
                    getDouble(meal.getFiber())));

            List<UserMealFood> foods = meal.getFoods();
            if (foods != null && !foods.isEmpty()) {
                for (UserMealFood food : foods) {
                    sb.append(String.format("  - 食材：%s（类别：%s），重量：%dg\n",
                            food.getName(), food.getCategory(), food.getAmount()));
                }
            } else {
                sb.append("  - 无食材明细记录\n");
            }
        }

        sb.append("请根据以上饮食数据，提供专业、简明的健康饮食建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
        userMealAdviceMapper.insertAdvice(userId, "day", date, advice);
        return advice;
    }

    /**
 * 获取周建议（过去 7 天，详细饮食明细）
 */
public String getWeeklyAdvice(Integer userId) {
    LocalDate startOfWeek = LocalDate.now().minusDays(6);
    String cached = userMealAdviceMapper.findAdvice(userId, "week", startOfWeek);
    if (cached != null) return cached;

    // 查询过去7天所有详细饮食记录（含食材）
    List<UserMeal> meals = userMealMapper.findMealsBetween(userId, startOfWeek, LocalDate.now());
    if (meals == null || meals.isEmpty()) {
        return "过去七天未记录饮食信息，建议您保持良好饮食习惯。";
    }

    // 构造提示词字符串
    StringBuilder sb = new StringBuilder("请根据以下过去一周的详细饮食记录，给出简明健康饮食建议：\n");
    for (UserMeal meal : meals) {
        sb.append(String.format("日期：%s，时间：%s，餐次：%s，总热量：%.1f 千卡，蛋白质：%.1fg，脂肪：%.1fg，碳水：%.1fg，纤维：%.1fg\n",
                meal.getMealDate(), meal.getMealTime(), meal.getMealType(),
                getDouble(meal.getCalories()), getDouble(meal.getProtein()), getDouble(meal.getFat()),
                getDouble(meal.getCarbohydrate()), getDouble(meal.getFiber())));
        List<UserMealFood> foods = meal.getFoods();
        if (foods != null && !foods.isEmpty()) {
            sb.append("  食材明细：");
            for (UserMealFood food : foods) {
                sb.append(String.format("[%s: %s x %d克] ", food.getCategory(), food.getName(), food.getAmount()));
            }
            sb.append("\n");
        } else {
            sb.append("  无食材明细\n");
        }
    }
    sb.append("请基于以上信息，提供专业的饮食建议。");

    String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
    userMealAdviceMapper.insertAdvice(userId, "week", startOfWeek, advice);
    return advice;
}

/**
 * 获取月建议（本月详细饮食明细）
 */
public String getMonthlyAdvice(Integer userId) {
    LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1);
    String cached = userMealAdviceMapper.findAdvice(userId, "month", startOfMonth);
    if (cached != null) return cached;

    // 查询本月所有详细饮食记录（含食材）
    List<UserMeal> meals = userMealMapper.findMealsBetween(userId, startOfMonth, LocalDate.now());
    if (meals == null || meals.isEmpty()) {
        return "最近一个月无饮食数据，建议您坚持记录每日饮食。";
    }

    // 构造提示词字符串
    StringBuilder sb = new StringBuilder("请根据以下本月详细饮食记录，给出月度饮食建议：\n");
    for (UserMeal meal : meals) {
        sb.append(String.format("日期：%s，时间：%s，餐次：%s，总热量：%.1f 千卡，蛋白质：%.1fg，脂肪：%.1fg，碳水：%.1fg，纤维：%.1fg\n",
                meal.getMealDate(), meal.getMealTime(), meal.getMealType(),
                getDouble(meal.getCalories()), getDouble(meal.getProtein()), getDouble(meal.getFat()),
                getDouble(meal.getCarbohydrate()), getDouble(meal.getFiber())));
        List<UserMealFood> foods = meal.getFoods();
        if (foods != null && !foods.isEmpty()) {
            sb.append("  食材明细：");
            for (UserMealFood food : foods) {
                sb.append(String.format("[%s: %s x %d克] ", food.getCategory(), food.getName(), food.getAmount()));
            }
            sb.append("\n");
        } else {
            sb.append("  无食材明细\n");
        }
    }
    sb.append("请基于以上信息，提供专业的饮食建议。");

    String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
    userMealAdviceMapper.insertAdvice(userId, "month", startOfMonth, advice);
    return advice;
}


    /**
     * 清除所有用户的每日建议缓存
     */
    public void cleanDailyAdviceCache() {
        userMealAdviceMapper.deleteAdviceByType("day");
    }

    /**
     * 清除某用户的周/月建议缓存
     */
    public void cleanWeekAndMonthAdviceCache(Integer userId) {
        userMealAdviceMapper.deleteAdviceByUserAndType(userId, "day");
        userMealAdviceMapper.deleteAdviceByUserAndType(userId, "week");
        userMealAdviceMapper.deleteAdviceByUserAndType(userId, "month");
    }

    /**
     * 工具方法：安全获取 Double 值
     */
    private double getDouble(Object obj) {
        return obj instanceof Number ? ((Number) obj).doubleValue() : 0.0;
    }
}
